package cn.eagle.controller.email;


import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import com.jcbase.core.auth.anno.RequiresPermissions;
import com.jcbase.core.controller.JCBaseController;
import com.jcbase.core.util.JqGridModelUtils;
import com.jcbase.core.view.InvokeResult;
import com.jcbase.model.UserEmailTemplate;

import com.jfinal.plugin.activerecord.Page;

import cn.dreampie.mail.Mailer;


public class EmailController extends JCBaseController{

	@RequiresPermissions(value={"/email/template"})
	public void index() {		
		render("email_template_index.jsp");
	}
	@RequiresPermissions(value={"/email/template"})
	public void getListData() {
		Page<UserEmailTemplate> pageInfo=UserEmailTemplate.dao.getPage(this.getPage(), this.getRows(),this.getOrderby());
		this.renderJson(JqGridModelUtils.toJqGridView(pageInfo)); 
	}
	@RequiresPermissions(value={"/email/template"})
	public void addEmail(){
		Integer id=getParaToInt("id");
		String action="add";
		if(id!=null){
			this.setAttr("item", UserEmailTemplate.dao.findById(id));
			action="edit";
		}
		this.setAttr("action", action);
		render("email_addTemplate.jsp");
	}
	@RequiresPermissions(value={"/email/template"})
	public void saveEmail(){
		Integer id=getParaToInt("id");
		String title=getPara("title");	
		String content=getPara("content");		
		Integer status=getParaToInt("status");
		InvokeResult result=UserEmailTemplate.dao.saveUserEmailTemplate(id, title, content,
				 status);
		this.renderJson(result);
	}
	@RequiresPermissions(value={"/email/template"})
	public void delete(){
		Integer id =getParaToInt("id");
		InvokeResult result =UserEmailTemplate.dao.deleteEmailTemplate(id);
		this.renderJson(result);
		
	}
	@RequiresPermissions(value={"/email/template"})
	public void sendEmail(){
		
		Integer id =getParaToInt("id");
		UserEmailTemplate useremail=UserEmailTemplate.dao.findByIdLoadColumns(id, "title,content,status");
		String title=useremail.getStr("title");
		String content=useremail.getStr("content");
		int status=useremail.getInt("status");
		System.out.println(status);
		if(status==1){
			//发送邮件
			 try {
				Mailer.sendText(title, content, "422964429@qq.com");
			} catch (EmailException e) {
				
				e.printStackTrace();
			}
			InvokeResult result=InvokeResult.success();
			this.renderJson(result);
		}else{
			InvokeResult result=InvokeResult.failure(-2,"邮件模板未启用");
			this.renderJson(result);
		}
		
		
		
	}
}
